if(typeof(GOLBAL_DATA.alertConfig)=="undefined"||GOLBAL_DATA.alertConfig==null){
	GOLBAL_DATA.alertConfig={EmailAddress:""};
}

if(!GOLBAL_DATA.alertConfig.EmailAddress){
	GOLBAL_DATA.alertConfig.EmailAddress=QS_UserNAME;
}
if(GOLBAL_DATA.alertEmail){
	GOLBAL_DATA.alertConfig.EmailAddress=GOLBAL_DATA.alertEmail;
}

//as a cfg
var QS_Alert_window = function(){
    this.windowCfg = {
        title: 'Alert Settings',
        width: 650,
        height: 490,
        resizable: true,
        isGlobal: true,
        hasSettingPanel: false,
        closeAction: 'hide'
    };
	this.alertObj =null;
    this.init();
};

QS_Alert_window.prototype = {
    init: function(){
        this.initWindow();
        rtqWindowGroup.register(this.window);
    },
	hide:function(){
		this.window.hide();
	},
	show:function(){
		this.window.show();
		if(this.alertObj){
			this.alertObj.onWindowShow();
		}
        setTimeout(function(){
			if (QS_Alert_Data && QS_Alert_Data.getAllAlerts) {
           QS_Alert_Data.getAllAlerts(function(){
				if (QS_Alert_Data && QS_Alert_Data.updateCheckAlertList) {
					QS_Alert_Data.updateCheckAlertList();
				}
			});	
			}
		},2000)
	},
	windowReady:function(obj){
		var __qadf = QS_Alert_Data.FIELD;
        var typeList=[__qadf["Last Price"],__qadf["Chg%"],__qadf["Volume"],__qadf["% 52WHigh"],__qadf["% 52WLow"],__qadf["> 52 Wk H"],__qadf["< 52 Wk L"]];
		var self = this;
        var settingObj = new QS_Alert_Setting_Plugin({typeList:typeList});
        //var logObj = new QS_Alert_Log_Plugin();
        self.alertObj = new QS_Alert(obj.contentEl, {
            setting: settingObj
        }, {
            onHide: function(){
                self.hide();
            }
        });
	},
    initWindow: function(){
        var self = this;
        this.window = new Util.RtqWindow(document.body, {
            windowReady: function(obj){
                self.windowReady(obj);
            },
			onResized:function(win,w,h){
				self.alertObj.changeOutSize(w,h);
			}
        }, this.windowCfg);
    }
};
var QSEMPTYFUNCTION=function(){return "";}
/*
 * REQUIRE@UI(checkbox,tabmenu,button)
 */
var QS_Alert = function(container,FI,callback,cfg){
	this.container = container;
	this.el = null;
	this.elSegment={};
	this.FI = $.extend(this.getInterface(),FI);
	this.settingEl = null;
	this.logEl = null;
	this.cfg = $.extend({setting:true,log:true},cfg);
	this.callback = $.extend({onHide:function(){}},callback);
	this.publicObj=null;
	this.init();
};
QS_Alert.prototype={
	getInterface:function(){
		var FI = {setting:{
			getHTML:QSEMPTYFUNCTION,
			setEl:QSEMPTYFUNCTION,
			hide:QSEMPTYFUNCTION,
			show:QSEMPTYFUNCTION,
			changeOutSize:QSEMPTYFUNCTION
		},log:{
			getHTML:QSEMPTYFUNCTION,
            setEl:QSEMPTYFUNCTION,
            hide:QSEMPTYFUNCTION,
            show:QSEMPTYFUNCTION,
			changeOutSize:QSEMPTYFUNCTION
		}}
		return FI;
	},
	changeOutSize:function(w,h){
		this.FI.setting.changeOutSize(w,h-109-28);
		if(typeof(this.FI.log.changeOutSize)=="function"){
			this.FI.log.changeOutSize(w,h-55);
		}
	},
	_buildPublicObj:function(){
		this.publicObj = {};
		this.publicObj.doClose=this.close;
		this.publicObj.callback = this.callback;
	},
	close:function(){
	   this.callback.onHide();
	},
	onWindowShow:function(){
		this.FI.setting.show();
	},
	init:function(){
		this._buildPublicObj();
		for(var i in this.FI){
			this.FI[i].host = this.publicObj;
		}
		this.el = $(this.getHTML()).appendTo(this.container);
		if(this.cfg.setting){
			var settingEl = $(this.FI.setting.getHTML());
			this.el.append(settingEl);
			this.FI.setting.setEl(settingEl);
			this.FI.setting.init();
			this.FI.setting.changeOutSize(this.container.width(),this.container.height()-109);
			this.FI.setting.hide();
		}
		if(this.cfg.log){
            var logEl = $(this.FI.log.getHTML());
            this.el.append(logEl);
            this.FI.log.setEl(logEl);
			//this.FI.log.init();
			this.FI.log.hide();
			//this.FI.log.changeOutSize(this.container.width(),this.container.height()-55);
        }
		if(this.cfg.setting&&this.cfg.log){
			this._buildTabmenu(this.el.find(".qs-alert-tabmenu-wrap"));
		}else{
            if (this.cfg.setting) {
                this.FI.log.hide();
                this.FI["setting"].show();
            } else if (this.cfg.log) {
                this.FI.log.init();
                this.FI.setting.hide();
                this.FI["log"].show();
            }
                
		}
	},
	_buildTabmenu:function(container){
		var self = this;
        var tabmenu = new Util.TabMenu(container, [{
            txt: "Setting",
            val: "setting",
			closable:false
        }
//		, {
//            txt: "History",
//            val: "log",
//            closable:false
//        }
		], {
            onActive: function(tab){
				if(tab.id=="setting"){
					self.FI.log.hide();
				}else if(tab.id=="log"){
					self.FI.log.init();
					self.FI.setting.hide();
				}
				self.FI[tab.id].show();
				if(tab.id=="log"&&typeof(self.FI.log.changeOutSize)=="function"){
                    self.FI.log.changeOutSize(self.container.width(),self.container.height()-30);
                }else{
					self.FI.setting.changeOutSize(self.container.width(),self.container.height()-109);
				}
            }
        }, {
            tabsList: false
        });
	},
	getHTML:function(){
	   return "<div class='qs-alert'><div class='qs-alert-tabmenu-wrap'></div></div>";
	}
};
QS_Alert_Data_LABEL={
        price:"userTargetPrice",
        percentage:"userTargetPercentage",
        volume:"userVolume",
        weekhigh52:"user52weekHigh",
        weeklow52:"user52weekLow",
        weekhigh52perc:"user52weekHighPercentage",
        weeklow52perc:"user52weekLowPercentage",
        weekhigh52percRead:"user52weekHighPerc",
        weeklow52percRead:"user52weekLowPerc",
        userSize:"userSize",
        userTargetChange:"userTargetChange"
 };
/*
 * REQUIRE(DBHelper,common)
 */
var QS_Alert_Data={
	LABEL:{
        price:"userTargetPrice",
        percentage:"userTargetPercentage",
        volume:"userVolume",
        weekhigh52:"user52weekHigh",
        weeklow52:"user52weekLow",
        weekhigh52perc:"user52weekHighPercentage",
        weeklow52perc:"user52weekLowPercentage",
        weekhigh52percRead:"user52weekHighPerc",
        weeklow52percRead:"user52weekLowPerc",
        userSize:"userSize",
        userTargetChange:"userTargetChange"
    },
	FIELD:{
		"Last Price":{val:"Last Price",txt:"Last Price",section:["00011","00012","00013","00014","00015"],label:QS_Alert_Data_LABEL.price},
        "lastpriceprec":{val:"Last Price%",txt:"Last Price%",section:["00016","00017","00018","00019","00020"],label:QS_Alert_Data_LABEL.price},
        "Chg%":{val:"Chg%",txt:"Chg%",section:["00001","00005","00003","00007","00009"],label:QS_Alert_Data_LABEL.percentage},
        "Chg% high vol":{val:"Chg% high vol",txt:"Chg% high vol",title:"Last Price [>=,<=] x% of previous last price &&Volume >= 2*(30 day Average Volume)",section:["00002","00006","00004","00008","00010"],label:QS_Alert_Data_LABEL.percentage},
        "Volume":{val:"Volume",txt:"Volume",section:["00022","00023","00024","00025","00026"],label:QS_Alert_Data_LABEL.volume},
        "% 52WHigh":{val:"% 52WHigh",txt:"% 52WHigh",section:["00039","00040","00041","00042","00043"],label:QS_Alert_Data_LABEL.weekhigh52perc},
        "% 52WLow":{val:"% 52WLow",txt:"% 52WLow",section:["00044","00045","00046","00047","00048"],label:QS_Alert_Data_LABEL.weeklow52perc},
        "52 Wk L":{val:"52 Wk L",txt:"52 Wk L",section:["00034","00035","00036","00037","00038"],label:QS_Alert_Data_LABEL.weeklow52},
        "52 Wk H":{val:"52 Wk H",txt:"52 Wk H",section:["00029","00030","00031","00032","00033"],label:QS_Alert_Data_LABEL.weekhigh52},
        "> 52 Wk H":{val:"> 52 Wk H",txt:"> 52 Wk H",title:"Last price > previous 52 week high value ",section:["00027"],label:""},
        "< 52 Wk L":{val:"< 52 Wk L",txt:"< 52 Wk L",title:"Last price < previous 52 week low value ",section:["00028"],label:""},
        "High vol":{val:"High vol",txt:"High vol",title:"Volume >= 2*(30 day Average Volume)",section:["00021"],label:""},
		"Last price - prev close":{title:"Price [>=,<=] x of prev close",val:"Last price - prev close",txt:"Last price - prev close",section:["00049","00050","00051","00052","00053"],label:QS_Alert_Data_LABEL.userTargetChange},
		"Ask price - prev close":{title:"Ask Price [>=,<=] x of prev close",val:"Ask price - prev close",txt:"Ask price - prev close",section:["00054","00055","00056","00057","00058"],label:QS_Alert_Data_LABEL.userTargetChange},
		"Bid price - prev close":{title:"Bid Price [>=,<=] x of prev close",val:"Bid price - prev close",txt:"Bid price - prev close",section:["00059","00060","00061","00062","00063"],label:QS_Alert_Data_LABEL.userTargetChange},
		"(Ask price - prev close)*100 / prev close":{title:"Ask Price [>=,<=] x% prev close",val:"(Ask price - prev close)*100 / prev close",txt:"(Ask price - prev close)*100 / prev close",section:["00064","00065","00066","00067","00068"],label:QS_Alert_Data_LABEL.percentage},
		"(Bid price - prev close)*100 / prev close":{title:"Bid Price [>=,<=] x% prev close",val:"(Bid price - prev close)*100 / prev close",txt:"(Bid price - prev close)*100 / prev close",section:["00069","00070","00071","00072","00073"],label:QS_Alert_Data_LABEL.percentage},
		"(Ask price on high vol - prev close)*100 / prev close":{title:"Ask Price [>=,<=] x% prev close on high vol",val:"(Ask price on high vol - prev close)*100 / prev close",txt:"(Ask price on high vol - prev close)*100 / prev close",section:["00074","00075","00076","00077","00078"],label:QS_Alert_Data_LABEL.percentage},
		"(Bid price on high vol - prev close)*100 / prev close":{title:"Bid Price [>=,<=] x% prev close on high vol",val:"(Bid price on high vol - prev close)*100 / prev close",txt:"(Bid price on high vol - prev close)*100 / prev close",section:["00079","00080","00081","00082","00083"],label:QS_Alert_Data_LABEL.percentage},
		"Ask Price":{val:"Ask Price",txt:"Ask Price",section:["00084","00085","00086","00087","00088"],label:QS_Alert_Data_LABEL.price},
		"Bid Price":{val:"Bid Price",txt:"Bid Price",section:["00089","00090","00091","00092","00093"],label:QS_Alert_Data_LABEL.price},
		//"Ask Price > x%":{val:"Ask Price > x%",txt:"Ask Price > x%",section:["00094","00095","00096","00097","00098"],label:QS_Alert_Data_LABEL.price},
		//"Bid Price > x%":{val:"Bid Price > x%",txt:"Bid Price > x%",section:["00099","00100","00101","00102","00103"],label:QS_Alert_Data_LABEL.price},
		"Ask Size":{val:"Ask Size",txt:"Ask Size",section:["00104","00105","00106","00107","00108"],label:QS_Alert_Data_LABEL.userSize},
		"Bid Size":{val:"Bid Size",txt:"Bid Size",section:["00109","00110","00111","00112","00113"],label:QS_Alert_Data_LABEL.userSize},
		"Dividend distribution":{val:"Dividend distribution",txt:"Dividend distribution",section:["M0024"],label:""}
	},
	CONDITION:{
		"gt":{txt:">",val:">"},
		"ge":{txt:">=",val:">="},
		"lt":{txt:"<",val:"<"},
		"le":{txt:"<=",val:"<="},
		"eq":{txt:"=",val:"="}
	},
	idType:"SC",
	tickerValidation: null,
	getAlert:function(callback){
		if (GOLBAL_DATA.alertSubscribeList  != null) {
			var  obj = GOLBAL_DATA.alertSubscribeList ;
            if (obj.list != null && obj.list.length > 0) {
                var list = obj.list, lg = obj.list.length,temp={},arr=[],alertData=null;
                for (var i = 0; i < lg; i++) {
					temp = list[i];
					alertData=$.extend(true,{},QS_Alert_Data.ID_FieldAndCondition_Mapping[temp.alertType]);
					if(alertData.label=="user52weekHighPercentage"){
						//alertData.label="user52weekHighPerc";
					}
					if(alertData.label=="user52weekLowPercentage"){
                        //alertData.label="user52weekLowPerc";
                    }
					arr.push({name:temp.tickerName,orginActive:temp.active,orginEmail:temp.alertOutput,active:temp.active=="ACTIVE",email:temp.alertOutput.indexOf("EMAIL")>-1,alertId:temp.subscriptionId,alertType:temp.alertType,pid:temp.performanceId,value:temp[alertData.label],type:alertData.field,operator:alertData.condition,action:"<a href='javascript:void(0);' class='qs-alert-datagrid-edit'>Edit</a><a href='javascript:void(0);' class='qs-alert-datagrid-delete'>Delete</a>"});
                }
                
                if (!QS_Alert_Data.tickerValidation) {
                    QS_Alert_Data.tickerValidation = new tickerValidation(1);
                    if (typeof(QS_Alert_Data.tickerValidation.needFilterSecurityType) != "undefined") {
                        QS_Alert_Data.tickerValidation.needFilterSecurityType = false;
                    }
                }
//                var self = this;
                var alertList = arr;
                var pidList = [];
                for (var i in alertList) {
                    if (alertList[i].pid) {
                        pidList.push(alertList[i].pid);
                    }
                }
                QS_Alert_Data.tickerValidation.checkTickers(pidList, function(o){
					var tempKey = "",t="";
					for(var k =0;k<arr.length;k++){
						tempKey =gIdMap[arr[k].pid];
						if(typeof(tempKey)=="undefined"){
							continue;
						}
						t = gData[tempKey].ticker;
						if(gData[tempKey].clientTicker){
							t = gData[tempKey].clientTicker;
						}
						arr[k].name=t;
					}
					if(typeof(callback)=="function"){
						callback(arr);
					}
                }, true);
				//return arr;
            }
        }
		return [];
	},
	tickerValidationClient:null,
	getClientTicker:function(pidList,callback){
        if (!QS_Alert_Data.tickerValidationClient) {
            QS_Alert_Data.tickerValidationClient = new tickerValidation(1);
            if (typeof(QS_Alert_Data.tickerValidationClient.needFilterSecurityType) != "undefined") {
                QS_Alert_Data.tickerValidationClient.needFilterSecurityType = false;
            }
        }
		QS_Alert_Data.tickerValidationClient.checkTickers(pidList, function(o){
                    if(typeof(callback)=="function"){
						var t = gData[o].ticker;
						if(gData[o].clientTicker){
							t=gData[o].clientTicker;
						}
                        callback(t);
                    }
         }, false);
	},
	_getAlertIdTypeByFieldAndCondition:function(field,condition){
		if(!field||!condition){
			throw new Error("Lack of necessary parameters.");
		}
		var temp  =null;
		for(var i in QS_Alert_Data.ID_FieldAndCondition_Mapping){
			temp = QS_Alert_Data.ID_FieldAndCondition_Mapping[i];
			if(temp.condition==""){
				if (field == temp.field) {
                    temp.alerttype = i;
                    return temp;
                }
			}else{
                if (field == temp.field && condition == temp.condition) {
                    temp.alerttype = i;
                    return temp;
                }
			}
		}
		return false;
	},
	getLabelByAlertType:function(type){
		return QS_Alert_Data.ID_FieldAndCondition_Mapping[type].label;
	},
	updateAlert:function(data,callback){
        var alertInfo = QS_Alert_Data._getAlertIdTypeByFieldAndCondition(data.type,data.operator);
        var idtype = data.idtype?data.idtype:QS_Alert_Data.idType;
		var email = data.email?"EMAIL":"";//data.email.indexOf("checked")>-1?"Email":"Notification";
		if(GOLBAL_DATA.alertConfig.EmailAddress==""){
			if($(".qs-alert .toleft .qs-ui-ipt").val().length>0){
				Util.message(TEXT.Alert.saveEmailFirst);
			}else{
				Util.message(TEXT.Alert.emailIsEmpty);
			}
            return;
        }
        DBHelper.updateAlert(data.alertId,alertInfo.alerttype,data.value,alertInfo.label,"None",GOLBAL_DATA.alertConfig.EmailAddress,function(outData){
            if(callback){
                callback($.evalJSON(outData));
            }
        });
	},
	deleteAlert:function(key,callback){
		DBHelper.deleteAlert(key,GOLBAL_DATA.alertConfig.EmailAddress,function(outData){
			if(callback){
                callback($.evalJSON(outData));
            }
		})
	},
	getAlertLogs:function(callback){
		DBHelper.loadAlertLog(function(outData){
            if(callback){
                callback($.evalJSON(outData));
            }
        })
	},
	getAllAlerts:function(callback,needUpdate,order){
		DBHelper.getAllAlerts(function(outData){
			var data = $.evalJSON(outData);
			if(GOLBAL_DATA.alertSubscribeList){
				GOLBAL_DATA.alertSubscribeList=data;
			}
			if(callback){
                callback(data);
            }
        },order?order:"")
	},
	addAlert:function(data,callback){
		var alertInfo = QS_Alert_Data._getAlertIdTypeByFieldAndCondition(data.type,data.operator);
		var idtype = data.idtype?data.idtype:QS_Alert_Data.idType;
		var email = data.email?"EMAIL":"";
		if(GOLBAL_DATA.alertConfig.EmailAddress==""){
			if($(".qs-alert .toleft .qs-ui-ipt").val().length>0){
                Util.message(TEXT.Alert.saveEmailFirst);
            }else{
                Util.message(TEXT.Alert.emailIsEmpty);
            }
			return;
		}
		QS_Alert_Data.getClientTicker([data.dispalyTicker],function(clientTicker){
            data.dispalyTicker = clientTicker;
            DBHelper.addAlert(alertInfo.alerttype, idtype, data.name, data.dispalyTicker, data.value, alertInfo.label, "None", GOLBAL_DATA.alertConfig.EmailAddress, function(outData){
                if (callback) {
                    callback($.evalJSON(outData));
                }
            });
        });
	},
	operateAlert:function(data,callback){
        DBHelper.operateAlert(data.alertid,data.email,data.type,function(outData){
            if(callback){
                callback($.evalJSON(outData));
            }
        });
    },
	updateCheckAlertList:function(){
        if (!QS_Alert_Data.tickerValidation) {
            QS_Alert_Data.tickerValidation = new tickerValidation(1);
			if(typeof(QS_Alert_Data.tickerValidation.needFilterSecurityType)!="undefined"){
				QS_Alert_Data.tickerValidation.needFilterSecurityType=false;
			}
        }
        var self = this;
        QS_Alert_Data.getAlert(function(alertList){
            var pidList = [];
                var t = null, pid = null;
                var map = {}, exchpid = null;
                for (var i in alertList) {
                    t = alertList[i];
                    pid = t.pid;
                    exchpid = gIdMap[pid];
                    if (exchpid && gData[exchpid]) {
                        alertList[i]["name"] = gData[exchpid].ticker;
                    }
                    if (!map[exchpid]) {
                        map[exchpid] = {};
                    }
					var ttype = t.type;
					if(ttype=="Last Price"){
						ttype="LastPrice";
					}
                    if (!map[exchpid][ttype]) {
                        map[exchpid][ttype] = [];
                    }
                    
					var isNewAlert = true;
					if(QS_Alert_Data.alertCheckList==null){
                        map[exchpid][ttype].push({
                            Op: t.operator,
                            Tick: t.alertId,
                            IsExpire: false,
                            Value: t.value
                        });
					}else{
						QS_Alert_Data.addAlertToAlertCheckList(t);
					}
                }
                if (QS_Alert_Data.alertCheckList == null) {
                    QS_Alert_Data.alertCheckList = map;
                }
                for (var i in map) {
                    updateWatchlistAlert(i, true, QS_Alert_Data.alertCheckList);
                }
        });
        
    },
	addAlertToAlertCheckList:function(d){
		if(!QS_Alert_Data.alertCheckList){
			return;
		}
		var ttype = d.type;
		if(ttype=="Last Price"){
                        ttype="LastPrice";
        }
		if(!d.pid||typeof(d.alertId)=="undefined"||d.alertId==""){
			return;
		}
		var gId = gIdMap[d.pid];
		if(!QS_Alert_Data.alertCheckList[gId]){
			QS_Alert_Data.alertCheckList[gId]={};
		}
		if(!QS_Alert_Data.alertCheckList[gId][ttype]){
			QS_Alert_Data.alertCheckList[gId][ttype]=[];
		}
		var isNewAlert = true;
		for(var i =0;i<QS_Alert_Data.alertCheckList[gId][ttype].length;i++){
			if(typeof(QS_Alert_Data.alertCheckList[gId][ttype][i].Tick)=="undefined"){
				
			}else if(QS_Alert_Data.alertCheckList[gId][ttype][i].Tick==d.alertId){
                isNewAlert=false;
            }
        }
		if(isNewAlert){
			QS_Alert_Data.alertCheckList[gId][ttype].push({IsExpire:typeof(d.active)!="undefined"?!d.active:false,Op:d.operator,Tick:d.alertId,Value:d.value});
		}
	},
	updateAlertToAlertCheckListById:function(id,type){
        var t = QS_Alert_Data.alertCheckList;
		if(!t){
			return;
		}
        for (var i in t) {
			if(typeof(t[i])=="undefined"){
				continue;
			}
            for (var j in t[i]) {
                for (var k = 0; k < t[i][j].length; k++) {
                    if(t[i][j][k].Tick==id){
						var f = false;
						if(type<2){
							f=true;
						}
						QS_Alert_Data.alertCheckList[i][j][k].IsExpire=f;
						QS_Alert_Data.updateCheckAlertList();
					}
                }
            }
        }
    },
	updateAlertToAlertCheckList:function(d){
        var gId = gIdMap[d.pid];
		var ttype = d.type;
        if(ttype=="Last Price"){
                        ttype="LastPrice";
        }
        if(!QS_Alert_Data.alertCheckList[gId]||!QS_Alert_Data.alertCheckList[gId][ttype]||QS_Alert_Data.alertCheckList[gId][ttype].length==0){
            return false;
        }
        for(var i =0;i<QS_Alert_Data.alertCheckList[gId][ttype].length;i++){
			if(QS_Alert_Data.alertCheckList[gId][ttype][i].Tick==d.alertId){
				QS_Alert_Data.alertCheckList[gId][ttype][i].Op = d.operator;
				QS_Alert_Data.alertCheckList[gId][ttype][i].Value = d.value;
				QS_Alert_Data.alertCheckList[gId][ttype][i].IsExpire = false;
			}
		}
    },
	alertCheckList:null
};
QS_Alert_Data.ID_FieldAndCondition_Mapping={};
var tempCondition = [">",">=","<","<=","="];
for(var i in QS_Alert_Data.FIELD){
var temp = QS_Alert_Data.FIELD[i];
var j = temp.section;
var kk ={};
for(var k = 0;k<j.length;k++){
    kk={field:i,condition:j.length==1?"":tempCondition[k],label:temp.label}
    QS_Alert_Data.ID_FieldAndCondition_Mapping[j[k]]=kk;
}
}
var QS_Alert_Log_Plugin=function(){
	this.el = null;
	this.grid = null;
};
QS_Alert_Log_Plugin.prototype={
	init:function(){
		if(this.grid!=null){
			return;
		}
		this.grid = new Util.DataGrid(this.el, {}, {
                column: this._getColumnList(),
                indexColKey: 'alertId',
                rowLayout: 'grid',
                cellResize: false,
                sortable: false,
                cellRearrange: true,
                showYScrollbar: true,
                autoWidth: true,
                rowSelectable:false,
                rowDragable: false,
                rowDropable: false,
				autoHeight:false,
                rowDragDropGroup: 'gridDDGroup'
            }, {
                
            });
	   var self = this;
		QS_Alert_Data.getAlertLogs(function(data){
			self._bindData(data.list);
		});
	},
	changeOutSize:function(w,h){
		if(this.grid){
			this.grid.resize(w,h);
		}
	},
	_bindData:function(data){
		var temp = null,alertData=null,arr=[];
		for(var i =0;i<data.length;i++){
			temp = data[i];
			alertData=QS_Alert_Data.ID_FieldAndCondition_Mapping[temp.alertType];
			arr.push({alertId:temp.alertInfoId,name:temp.ticker||temp.performanceId,type:alertData.field,operator:alertData.condition,value:temp[alertData.label],firedtime:this._getDateFormat(temp.alertTime)});
		}
		this.grid.reBindData(arr);
	},
	_getDateFormat:function(d){
	    var d = new Date(d);
		return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()+" "+d.getHours()+":"+d.getMinutes();
	},
	_getColumnList:function(){
        var headerList = [{
            header: "Ticker",
            dataIndex: 'name',
            dataType: 'string',
            width: 110
        }, {
            header: "Type",
            dataIndex: 'type',
            dataType: 'string',
            width: 110
        }, {
            header: "Operator",
            dataIndex: 'operator',
            dataType: 'string',
            width: 110
        }, {
            header: "Value",
            dataIndex: 'value',
            dataType: 'string',
            width: 110
        }, {
            header: "Fired Time",
            dataIndex: 'firedtime',
            type: 'string',
            width: 110
        }];
        return headerList;
    },
	getHTML:function(){
		var logDom = "<div class='qs-alert-log'>"+
                       "</div>";
	   return logDom;
	},
	show:function(){
        this.el.show();
		//this.changeOutSize();
    },
    hide:function(){
        this.el.hide();
    },
	setEl:function(el){
        this.el = el;
    }
};
var QS_Alert_Setting_Plugin=function(cfg){
	this.host=null;
    this.el = null;
    this.elSegment={};
	this.editPid = null;
	this.editTicker = null;
	this.autoCompleteIndex = 0;
	var __qadf = QS_Alert_Data.FIELD;
	this.defaultTypeList=[__qadf["Last Price"],__qadf["Chg%"],__qadf["Chg% high vol"],__qadf["Volume"],__qadf["% 52WHigh"],__qadf["% 52WLow"],__qadf["52 Wk L"],__qadf["52 Wk H"],__qadf["> 52 Wk H"],__qadf["< 52 Wk L"],__qadf["High vol"],__qadf["Last price - prev close"],__qadf["Ask price - prev close"],__qadf["Bid price - prev close"],__qadf["(Ask price - prev close)*100 / prev close"],__qadf["(Bid price - prev close)*100 / prev close"],__qadf["(Ask price on high vol - prev close)*100 / prev close"],__qadf["(Bid price on high vol - prev close)*100 / prev close"],__qadf["Ask Price"],__qadf["Bid Price"],__qadf["Ask Size"],__qadf["Bid Size"],__qadf["Dividend distribution"]];
	this.cfg = $.extend(true,{typeList:this.defaultTypeList,operateList:this._getDefaultOperatorList(),showCheckbox:true,showClose:true,autoHeight:false},{});
	this._initConfig(cfg);
	this.alertCheckList=[];
	this.order="";//"ASC,DESC"
	this.timerObj = null;
	delete __qadf;
};
QS_Alert_Setting_Plugin.prototype={
	_initConfig:function(cfg){
		if(cfg){
            if (cfg.operateList) {
                this.cfg.operateList = [];
                this.cfg.operateList = cfg.operateList;
            }
            if (typeof(cfg.showCheckbox) != "undefined") {
                this.cfg.showCheckbox = cfg.showCheckbox;
            }
            if (typeof(cfg.showClose) != "undefined") {
                this.cfg.showClose = cfg.showClose;
            }
			if (typeof(cfg.autoHeight) != "undefined") {
                this.cfg.autoHeight = cfg.autoHeight;
            }
			if (typeof(cfg.typeList) != "undefined") {
                this.cfg.typeList = cfg.typeList;
            }
		}
	},
	onHeightChange:function(){
	},
	_getDefaultOperatorList:function(){
		var cfg = [];
		var tf=QS_Alert_Data.FIELD;
		var tc = QS_Alert_Data.CONDITION;
		var tcAll = [tc.gt,tc.ge,tc.lt,tc.le,tc.eq];
		cfg[tf["Last Price"].val]=tcAll;
		cfg[tf["Last Price"].val]=tcAll;
		cfg[tf["lastpriceprec"].val]=tcAll;
		cfg[tf["Chg%"].val]=tcAll;
		cfg[tf["Chg% high vol"].val]=tcAll;
		cfg[tf["Volume"].val]=tcAll;
		cfg[tf["% 52WHigh"].val]=tcAll;
		cfg[tf["% 52WLow"].val]=tcAll;
		cfg[tf["52 Wk L"].val]=tcAll;
		cfg[tf["52 Wk H"].val]=tcAll;
		cfg[tf["> 52 Wk H"].val]=[tc.gt];
		cfg[tf["< 52 Wk L"].val]=[tc.lt];
		cfg[tf["High vol"].val]=[tc.ge];
		return cfg;
	},
	changeOutSize:function(w,h){
		if(this.cfg.showCheckbox&&h){
			h = h -30;
		}
		this.grid.ellipsisDom();
		//this.grid.resize(w,h);
		if(!this.cfg.autoHeight){
			this.grid.resize(w,h);
		}
		var orignStatus=this.grid.scrollPanel.scrollbarY.isShow;
		if(this.timerObj){
			clearInterval(this.timerObj);
		}
		var self = this,count =0,newStatus =null;
		this.editRow.reSize();
		this.grid.ellipsisDom();
		this.timerObj =setInterval(function(){
			newStatus=self.grid.scrollPanel.scrollbarY.isShow;
			if(count==10||orignStatus!=newStatus){
				clearInterval(self.timerObj);
				//self.editRow.show(self.editRow.blankRow);
				var rows = self.grid.rows;
				for(var r in rows){
					self.editRow.setEditRowWidth(rows[r].el.width()+2);
					//self.editRow.reSize(!newStatus);
					break;
				}
			}
			count++;
		},10);
	},
	_getAllAlerts:function(flag){
		var self = this;
		QS_Alert_Data.getAllAlerts(function(){
             QS_Alert_Data.updateCheckAlertList();
			 self.onHeightChange();
        },flag);
	},
	_reverseOrder:function(o){
		if(o=="asc"){
			return "desc";
		}
		if(o=="desc"){
            return "asc";
        }
	},
	init:function(){
		var self =this;
        this.elSegment.hd=this.el.find(".hd");
        this.elSegment.bd = this.el.find(".bd");
        this.elSegment.ft = this.el.find(".ft");
        this.elSegment.btnSave = this.elSegment.ft.find(".qs-alert-btn-save");
        this.elSegment.btnClose = this.elSegment.ft.find(".qs-alert-btn-close");
        this.elSegment.checkboxgroupWrap = this.elSegment.ft.find(".qs-alert-checkboxgroup-wrap");
		this.elSegment.gridWrap = this.elSegment.bd.find(".qs-alert-datagrid-wrap");
		this.elSegment.emailInput = this.elSegment.ft.find(".toleft input");
		//this.elSegment.emailInput.val(QS_UserNAME);
//		this.elSegment.emailInput.bind("blur",function(){
//			if(GOLBAL_DATA&&GOLBAL_DATA.alertConfig&&typeof(GOLBAL_DATA.alertConfig.EmailAddress)!="undefined"){
//				self.elSegment.emailInput.val(GOLBAL_DATA.alertConfig.EmailAddress);
//			}
//		})
		var timerObj = null;
        this.checkbox = new Util.ButtonGroup(this.elSegment.checkboxgroupWrap, [{txt:"Pop up",val:"PopupInform"},{txt:"Audio",val:"SoundInform"}], {//,{txt:"Email",val:"EmailInform",disable:true}
            onClick: function(v,b){
				if(!timerObj){
					clearTimeout(timerObj);
				}
				timerObj=setTimeout(function(){
					self.saveAlertCfg(2);
				},1000)
            }
        }, {
            type: 'checkbox',
            vertical: false
        });
		this.elSegment.btnSave.bind("click",function(){
			//self.host.doSave();
			self.saveAlertCfg(1);
		})
		this.elSegment.btnClose.bind("click",function(){
            self.host.doClose();
        });
		 this.grid = new Util.DataGrid(this.elSegment.gridWrap, {}, {
                column: this._getColumnList(),
                indexColKey: 'alertId',
                rowLayout: 'grid',
                cellResize: false,
                sortable: true,
                cellRearrange: false,
                showYScrollbar: true,
                autoWidth: true,
                rowSelectable:true,
                rowDragable: false,
                rowDropable: false,
				rowInvertSelect:false,
				autoHeight:this.cfg.autoHeight,
                rowDragDropGroup: 'gridDDGroup'
            }, {
                onRowSelected:function(e, row){
					if ($(e.target).attr("class").indexOf("qs-alert-datagrid-edit") != -1) {
					   self.editRow.show(row);
					} else if ($(e.target).attr("class").indexOf("qs-alert-datagrid-delete") != -1) {
						Util.confirm("Are you sure you want to delete this alert?",function(f){
							if(f){
                                QS_Alert_Data.deleteAlert(row.id, function(outData){
									if(outData&&outData.result!="fail"){
										self.grid.removeRow(row.id);
                                        self._getAllAlerts(true);
									}else{
										alertTeamMessage(outData,["Delete alert successfully.","Delete alert failed."]);
									}
                                });
							}
						});
					}
				}
            });
		//var alertList = QS_Alert_Data.getAlert();
	    //this._updateCheckAlertList();
		//this.grid.reBindData(QS_Alert_Data.getAlert());
		//this.checkAlert();
		this.grid.sortByCell=function(cellKey, order){
			if(cellKey!="name"){
				return;
			}
			if(self.order==""){
				self.order = "desc";
			}
			self.order = self._reverseOrder(self.order);
			QS_Alert_Data.getAllAlerts(function(data){
				QS_Alert_Data.getAlert(function(data){
					self.grid.reBindData(data);
					if(typeof(self.onHeightChange)=="function"){
						self.onHeightChange();
						
					}
				});
				//self.grid.reBindData(QS_Alert_Data.getAlert());
				self.grid.header.row.cells[cellKey].el.removeClass('rtq-grid-cell-sd');
				self.grid.header.row.cells[cellKey].el.removeClass('rtq-grid-cell-sa');
				if(self.order=="desc"){
					self.grid.header.row.cells[cellKey].el.addClass('rtq-grid-cell-sd');
				}else{
					self.grid.header.row.cells[cellKey].el.addClass('rtq-grid-cell-sa');
				}
			},null,self.order);
		}
        var editrow = new Util.DataGridEditRow(this.grid, {
			addRowEl:$(".qs-alert-addrow-wrap"),
            showOnClick: false,
            showOnDBclick: true,
            showAtTop: true,
			autoAddRow:false,
			autoSave:false
        }, {
            afterAdd: function(isSucceed, newRowData,datagridCallback){
                if (!isSucceed || !newRowData) {
                    return;
                }
				var useEditValue = false;
				if(newRowData.name.indexOf("__")!=-1){
					newRowData.name = newRowData.name.replace("__","").toUpperCase();
					newRowData.idtype="CS";
					GB_qsAutoCompleteBox.getPidByTicker("qs-alert-autocomplete-id-"+self.autoCompleteIndex,newRowData.name);
					useEditValue = true;
				}
				newRowData["dispalyTicker"]=newRowData.name;
                QS_Alert_Data.addAlert(newRowData, function(data){
					if(data.result=="fail"){
						alertTeamMessage(data,["Successfully.","Failed."]);
						return;
					}
					var tempTicker = newRowData.name;
					if(!useEditValue){
						newRowData.name = self.editTicker;
					}
					newRowData.value = parseFloat(newRowData.value).toFixed(2);
					newRowData.active=newRowData.active.indexOf("qs-datagrid-cell-checked")!=-1;
					var k = newRowData.type;
					if(k=="High vol"||k=="< 52 Wk L"||k=="> 52 Wk H"||k=="Dividend distribution"){
						newRowData.operator=" ";
						newRowData.value=" ";
					}
					if(typeof(datagridCallback)=="function"){
						datagridCallback();
					}
					newRowData.action="<a href='javascript:void(0);' class='qs-alert-datagrid-edit'>Edit</a><a href='javascript:void(0);' class='qs-alert-datagrid-delete'>Delete</a>";
					var tempAlertAddInfo=QS_Alert_Data._getAlertIdTypeByFieldAndCondition(newRowData.type,newRowData.operator);
					if(typeof(tempAlertAddInfo)!="undefined"&&tempAlertAddInfo.alerttype){
						newRowData.alertType =tempAlertAddInfo.alerttype;
					}
					QS_Alert_Data.getClientTicker([tempTicker],function(clientTicker){
						newRowData.name = clientTicker;
						self.grid.addRow(newRowData, data.subscriptionId, 0);
					});
					if(!newRowData.active){
						self._operateAlert(data.subscriptionId,1);
					}
//					QS_Alert_Data.getAllAlerts(function(){
//						//self._updateCheckAlertList();
//					},true);
                    QS_Alert_Data.addAlertToAlertCheckList($.extend(true,newRowData,{alertId:data.subscriptionId}));
					self._getAllAlerts(true);
					
                });
            },
            onShow: function(){
                
            },
			afterSave: function(isSucceed, editRowData,callback){
                if (!isSucceed || !editRowData) {
                    return;
                }
				var list = GOLBAL_DATA.alertSubscribeList.list;
				var sid = null;
				for(var i =0;list&&i<list.length;i++){
					if(list[i].subscriptionId==editRowData.alertId){
						sid = list[i].performanceId;
					}
				}
				editRowData.pid =sid;
				var originDowData = self.grid.rows[editRowData.alertId].data;
				var needToUpdateRow=false;
				if(originDowData){
					var tempAlertInfo=QS_Alert_Data._getAlertIdTypeByFieldAndCondition(editRowData.type,editRowData.operator);
					if(typeof(originDowData.alertType)!="undefined"&&tempAlertInfo.alerttype!=originDowData.alertType){
						needToUpdateRow=true;
					}
					var k = editRowData.type;
					if(k=="High vol"||k=="< 52 Wk L"||k=="> 52 Wk H"||k=="Dividend distribution"){
                        
                    }else if(originDowData.value!=editRowData.value){
						needToUpdateRow=true;
					}
				}
                var k = editRowData.type;
                var callbackAction = {};
                if (k == "High vol" || k == "< 52 Wk L" || k == "> 52 Wk H" || k == "Dividend distribution") {
                    callbackAction.needClearCol = "_value_operator_";
                }
				if(needToUpdateRow){
					
                    QS_Alert_Data.updateAlert(editRowData, function(data){
                        if (data && data.result == "success") {
                            if (callback) {
                                callback(editRowData.alertId,callbackAction);
                            }
							QS_Alert_Data.updateAlertToAlertCheckList($.extend(true,editRowData,{alertId:data.subscriptionId}));
                        } else {
							alertTeamMessage(data,["Successfully.","Failed."]);
                        }
                    });
				}else{
					if (callback) {
                      callback(editRowData.alertId,callbackAction);
                    }
				}
                self._checkNeedUpdateActiveStatus(editRowData.alertId,editRowData.active.indexOf("qs-datagrid-cell-checked")!=-1);
				
            }
        });
		this.editRow = editrow;
		this.initCfg(GOLBAL_DATA.alertConfig);
		editrow._columnCfg[1].editorObj.control.onChange=function(v,k){
			self._editorOnChange(editrow,"editorObj",v,k);
		}
		editrow._columnCfg[1].addObj.control.onChange=function(v,k){
            self._editorOnChange(editrow,"addObj",v,k);
        }
		QS_Alert_Data.getAlert(function(data){
			self.grid.reBindData(data);
			if(typeof(self.onHeightChange)=="function"){
                 self.onHeightChange();
           }
		})
		if(!this.cfg.showCheckbox){
            this.elSegment.checkboxgroupWrap.hide();
        }
		if(!this.cfg.showClose){
            this.elSegment.btnClose.hide();
        }
		//this.changeOutSize(200,400);
	},
    _editorOnChange:function(editrow,type,v,k){
        editrow._columnCfg[2][type].control.setDisable(false);
        editrow._columnCfg[3][type].control.prop("disabled", "");
		editrow._columnCfg[3][type].control.removeClass("qs-ui-ipt-disable");
        if (k == "High vol" || k == "< 52 Wk L" || k == "> 52 Wk H"||k=="Dividend distribution") {
            editrow._columnCfg[2][type].control.setDisable(true);
            editrow._columnCfg[3][type].control.prop("disabled", "disabled");
			editrow._columnCfg[3][type].control.addClass("qs-ui-ipt-disable");
        }
        editrow._columnCfg[2][type].control.rebindData(this.cfg.operateList[k]);
        editrow._columnCfg[2][type].control.data = this.cfg.operateList[k];
        editrow._columnCfg[2][type].control.selectItemByValue(this.cfg.operateList[k][0].val);
	},
	_checkNeedUpdateActiveStatus:function(id,newStatus){
		var self = this;
		var list = GOLBAL_DATA.alertSubscribeList.list;
		for(var i =0;i<list.length;i++){
			var t = list[i];
			if(t.subscriptionId==id){
				var type = 0;
				if(t.active.toUpperCase()=="ACTIVE"&&newStatus==false){
					type =1;
				}
				if(t.active.toUpperCase()=="SUSPENDED"&&newStatus==true){
                    type =2;
                }
				if(type!=0){
					this._operateAlert(id,type);
				}else{
					//QS_Alert_Data.getAllAlerts(null,true);
					self._getAllAlerts(true);
				}
				break;
			}
		}
	},
	_operateAlert:function(id,type){
		var self =this;
        QS_Alert_Data.operateAlert({
            alertid: id,
            email: GOLBAL_DATA.alertConfig.EmailAddress,
            type: type
        }, function(data){
            if (data.result == "fail") {
				 alertTeamMessage(data,["Successfully.","Failed."]);
            }else{
				//QS_Alert_Data.getAllAlerts(null,true);
				self._getAllAlerts(true);
				QS_Alert_Data.updateAlertToAlertCheckListById(id,type);
			}
        });
	},
	checkAlert:function(){
		for(var i in this.alertCheckList){
            //updateWatchlistAlert(i,true,this.alertCheckList);
		}
	},
	_getTypeList:function(){
		return [QS_Alert_Data.FIELD["Last Price"],QS_Alert_Data.FIELD["Chg%"],QS_Alert_Data.FIELD["Volume"],QS_Alert_Data.FIELD["% 52WHigh"],QS_Alert_Data.FIELD["% 52WLow"],QS_Alert_Data.FIELD["52 Wk L"],QS_Alert_Data.FIELD["52 Wk H"]];
	},
	_getOperatorList:function(){
		return [QS_Alert_Data.CONDITION.gt,QS_Alert_Data.CONDITION.ge,QS_Alert_Data.CONDITION.lt,QS_Alert_Data.CONDITION.le,QS_Alert_Data.CONDITION.eq];
	},
	___test:function(){
		
	},
	_getColumnList:function(){
		var self = this;
        var headerList = [{
            header: "Ticker",
            dataIndex: 'name',
            dataType: 'string',
			readonly:true,
            width: "20%",
			editor:{type:"custom",
			readonly:true,
			validator:function(v){
                if(v.replace(/ /g,"").replace("__","").length==0){
					Util.message(TEXT.Alert.requireTicker);
					return false;
				}
                return true;
            },
			renderer:function(editorCellDOM){
				var acbid = self.autoCompleteIndex++;
				var obj =$("<input id='qs-alert-autocomplete-id-"+acbid+"' class='qs-ui-ipt' type=text />").appendTo(editorCellDOM);
				GB_qsAutoCompleteBox.subscription("qs-alert-autocomplete-id-"+acbid,function(pid,data){
					obj.attr("editValue",pid);
					self.editTicker = data.ticker;
				},{needRemember:false});
				GB_qsAutoCompleteBox.hideAdvacedSearch();
				return obj;
			},
			getValue:function(editorCellDOM,isAdd){
				if(typeof(isAdd)!="undefined"&&isAdd==true){
					if($(this).val()==""){
						$(this).attr("editValue","");
						return "";
					}
					if($(this).attr("editValue")==""){
						var tempPid = GB_qsAutoCompleteBox.getPidByTicker($(this).attr("id"),$(this).val());
						if(typeof(tempPid)!="undefined"&&tempPid!=null&&tempPid!=""){
							$(this).attr("editValue",tempPid.pid);
                            self.editTicker = tempPid.ticker;
						}else{
							return "__"+$(this).val();
						}
					}
					return $(this).attr("editValue")||$(this).val();
				}else{
					return $(this).val();//for update
				}
			},
			setValue:function(value, width, editorCellDOM){
				if(typeof(value)!="undefined"&&value!=null){
					$(this).val(value);
				}
				if(value==""){
					$(this).attr("editValue",value);
				}
				if(width){
					$(this).width(width);
				}
			}
			}
        }, {
            header: "Type",
            dataIndex: 'type',
            dataType: 'string',
            width: "24.8%",
			ellipsis:false,
			editor: {
                type: 'dropdownlist',
                data: this.cfg.typeList
            }
        }, {
            header: "Operator",
            dataIndex: 'operator',
            dataType: 'string',
            width: "15%",
			ellipsis:false,
			editor: {
                type: 'dropdownlist',
                data: this.cfg.operateList[this.cfg.typeList[0].val]
            }
        }, {
            header: "Value",
            dataIndex: 'value',
            dataType: 'string',
            width: "20%",
			editor:{type:"text",
			validator:function(v,type){
				var data =v.replace(/ /g,"");
				if(data.length==0&&(!self.editRow._columnCfg[3].editorObj.control.attr("disabled")&&type=="update"||!self.editRow._columnCfg[3].addObj.control.attr("disabled")&&type=="add")){
					Util.message(TEXT.Alert.requireValue);
					return false;
				}
				
				if(isNaN(data)){
					Util.message(TEXT.Alert.invalidValue);
					return false;
				}
				return true;
			}}
        }, {
            header: "Active",
            dataIndex: 'active',
            type: 'string',
			className: 'qs-alert-datagrid-column-active',
            width: "8%",
			renderer:function(data){
				var str ="<div class='qs-datagrid-cell-checkbox'></div>";
				if(data){
					str ="<div class='qs-datagrid-cell-checkbox qs-datagrid-cell-checked'></div>";
				}
				return str;
			},
			editor: {
                type: 'checkbox',
				getValue:function(data){
                    var str = "<div class='qs-datagrid-cell-checkbox'></div>";
                    if (data) {
                        str = "<div class='qs-datagrid-cell-checkbox qs-datagrid-cell-checked'></div>";
                    }
                    return str;
				},
				//addAble:false,
				defaultValue:true
            }
        },
//		{
//            header: "Email",
//            dataIndex: 'email',
//			algin:"center",
//            type: 'string',
//            width: "10%",
//			className: 'qs-alert-datagrid-column-email',
////			rtq-grid-bd .col-email{}
//			renderer:function(data){
//                var str ="<div class='qs-datagrid-cell-checkbox'></div>";
//                if(data){
//                    str ="<div class='qs-datagrid-cell-checkbox qs-datagrid-cell-checked'></div>";
//                }
//                return str;
//            },
//			editor: {
//                type: 'checkbox',
//				defaultValue:true
//            }
//       }, 
		{
            header: "Actions",
            dataIndex: 'action',
			align:"right",
			className: 'qs-alert-datagrid-column-action',
			addAble:false,
            blankWhenEditting:true,
            width: "12%"
        }];
        return headerList;
    },
	show:function(){
		this.el.show();
		this.initCfg(GOLBAL_DATA.alertConfig);
	},
	hide:function(){
		this.el.hide();
	},
	setEl:function(el){
		this.el = el;
	},
	initCfg:function(cfg){
		this.checkbox.btns.SoundInform.inverse();
		this.checkbox.btns.PopupInform.inverse();
		//this.checkbox.btns.EmailInform.inverse();
		this.elSegment.emailInput.val(cfg.EmailAddress);
		this.elSegment.ft.find(".help-ico").attr("title","Alerts will be sent to "+cfg.EmailAddress);
		if(cfg.SoundInform){
			this.checkbox.btns.SoundInform.select();
		}
		if(cfg.PopupInform){
            this.checkbox.btns.PopupInform.select();
        }
		if(cfg.EmailInform){
           // this.checkbox.btns.EmailInform.select();
        }
	},
	saveAlertCfg:function(save){//0 or undefined is save all(email and check box),1 only save eamil,2 only save check box
		this.elSegment.ft.find(".help-ico").attr("title","Alerts will be sent to "+GOLBAL_DATA.alertConfig.EmailAddress);
		var cfg = null;
		if(typeof(GOLBAL_DATA.alertConfig)=="undefined"||typeof(GOLBAL_DATA.alertConfig.EmailAddress)=="undefined"){
			cfg={"FaxInform":0,"EmailInform":0,"EmailAddress":"","FaxAddress":"","UserId":0,"SoundInform":0,"PopupInform":0};
		}else{
			cfg=GOLBAL_DATA.alertConfig;
		}
		if(!cfg.UserId||cfg.UserId==0){
			cfg.UserId=QS_UserID;
		}
		if(typeof(save)=="undefined"||save==1){
            GOLBAL_DATA.alertConfig.EmailAddress= this.elSegment.emailInput.val();
            DBHelper.updateEmail(GOLBAL_DATA.alertConfig.EmailAddress,function(data){
                var o = data;
                if (typeof(data) == "string") {
                    o = $.evalJSON(data);
                }
				if(o&&o.errorCode&&o.errorCode=="55"){
					Util.message(TEXT.Alert.eamilSaveSuccessful );
				}else{
					alertTeamMessage(data,[TEXT.Alert.eamilSaveSuccessful ,TEXT.Alert.eamilSaveFaild]);
					if(o&&o.result!="fail"){
                        DBHelper.saveAlertConfig($.toJSON(cfg), function(data){
                        })
					}
				}
            })
        }else{
            if (typeof(save) == "undefined" || save == 2) {
                for (var i in this.checkbox.btns) {
                    cfg[i] = this.checkbox.btns[i].isSelected ? 1 : 0;
                }
            }
            DBHelper.saveAlertConfig($.toJSON(cfg), function(data){
                var o = $.evalJSON(data);
                if (o && o.message == "success") {
                    if (typeof(save) == "undefined" || save == 1) {
                        //Util.message(TEXT.Alert.eamilSaveSuccessful );
                    } else {
                        //Util.message(TEXT.Alert.eamilSaveFaild);
                    }
                }
            })
		}
		
	},
	getHTML:function(){
		 var settingDom = "<div class='qs-gd qs-alert-setting'>"+
                       "<div class='hd'>"+
                       "</div>"+
                       "<div class='bd'>"+
					       "<div class='ft clearfix'>"+
						          "<div class='qs-alert-add-title'>Add alert</div>"+
								  "<a href='javascript:void(0);' class='qs-ui-btn qs-alert-btn-save'>Save</a>"+
		                          "<div class='toleft'><label class='email-label'>Email address:</label><label title='Please type your email.' class='help-ico'>&nbsp;&nbsp;&nbsp;</label><input type='text' class='qs-ui-ipt'/></div>"+
                            "</div>"+
					       "<div class='qs-alert-addrow-wrap rtq-grid rtq-grid-auto'>"+
							   "<div class='qs-alert-addrow-title-wrap clearfix'>"+
	                           "</div>"+
						   "</div>"+
                           "<div class='qs-alert-datagrid-wrap'>"+
                           "</div>"+
                       "</div>"+
                       "<div class='ft'>"+
//					   	   "<div class='toleft'><label>Email:<input type='text' class='qs-ui-ipt'/></label></div>"+
//						   "<a href='javascript:void(0);' class='qs-ui-btn qs-alert-btn-close'>Close</a>"+  
//						   "<a href='javascript:void(0);' class='qs-ui-btn qs-alert-btn-save'>Save</a>"+
						   "<div class='qs-alert-checkboxgroup-wrap'></div>"+
                       "</div>"+
                   "</div>";
		return settingDom;
	}
};
var QS_Alert_PullHistoricalData_Plugin=function(){
	
};
QS_Alert_PullHistoricalData_Plugin.prototype={
	
};
var GB_Alert = null;

function getAlertFromDB(){
	
}
var alertAudioObj = null;

function updateWatchlistAlert(key,isUpdateStopedWachlist,condList) {  // check the alart when last price or volume value changing.
    var alert = -1;
	var cond = typeof(condList)=="undefined"?QS_Alert_Data.alertCheckList:condList;
    if (!cond) return;
	cond =cond[key];
	if (!cond) return;
    hasNoExpireCondiction = false;// there is validate condiction.
    hasCondiction = false;   // there is condiction.
    isBreak=false;
    for (var f in cond) {
        if(cond[f] == null || cond[f].length < 1) continue;
        var c, isHit, symbol, msg;
        for (var i = 0;i < cond[f].length; i++) {
            c = cond[f][i];  
            hasCondiction = true;
            if (gData[key]) {
                var condValue = NaN ;
                if(f == "% 52WHigh"||f == "> 52 Wk H"){
                    if(gData[key]["LastPrice"]&& gData[key]["st168"]){
                        if (f == "% 52WHigh") {
                            condValue = 100 * (gData[key]["LastPrice"] - gData[key]["st168"]) / gData[key]["st168"];
                        }else{
                            condValue =  gData[key]["st168"]- gData[key]["LastPrice"];  // if condValue < 0 meet the alert requirement
                        }
                    }
                }else if(f == "% 52WLow"||f == "< 52 Wk L"){
                    if(gData[key]["LastPrice"]&& gData[key]["st169"]){
                        if (f == "% 52WLow") {
                            condValue = 100 * (gData[key]["LastPrice"] - gData[key]["st169"]) / gData[key]["st169"];
                        }else{
                            condValue = gData[key]["LastPrice"]- gData[key]["st169"]; // if condValue < 0 meet the alert requirement
                        }
                    }
                }else{
                     condValue = gData[key][f]?gData[key][f]:NaN;
                }
                if(isNaN(condValue)) continue; // invalid condiction value.
                isHit = conditionFuncs[c.Op](condValue, c.Value);  // if or not hit the condiction
                if (isHit) {
                    if (!c.IsExpire) { //meet condiction
                        symbol = key.split(":")[1];
                        msg = String.format("Alert: {0} {1} {2} {3} Current Value: {4}<br/>", symbol, f, c.Op, c.Value, condValue);
                        if (GOLBAL_DATA.alertConfig.PopupInform==1&& Util && Util.message) {
                            Util.message(msg);
                        }
						if (GOLBAL_DATA.alertConfig.SoundInform==1) {
							if(!alertAudioObj){
								alertAudioObj=new Util.soundComponent({src:"IM/ding.wav"});
							}
                            alertAudioObj.play();
                        }
                        c.IsExpire = true;
                       // setAlertCondictionStuas(c.Tick);
                    }
                }else{
                    c.IsExpire=false;
                }
                if(!c.IsExpire) {
                    hasNoExpireCondiction = true;
                }
            }
        }
    }
    if (hasCondiction) {
       alert = 1;
    }
    if (hasNoExpireCondiction) {
       alert = 0;
    }
    if ( !gData[key] || !gData[key]["Alert"] || gData[key]["Alert"] != alert) {    // update alert in watchlist.
    if(!push.proxy){
		return;
	}
         var ws = push.proxy.getAllRegistedWatchlists();
         var updatedFileds = {};
         updatedFileds["Alert"] = {dataType:"i",oValue:"",value:alert};
         if(gData[key] == null) gData[key] = {};
         gData[key]["Alert"] = alert;
         for (var o in ws) {
              if (!isUpdateStopedWachlist&&ws[o].pause) continue;
              ws[o].updateData(key,updatedFileds); 
         }
    }
}
var conditionFuncs = {
    "<": function(a, b) { return a < b; },
    "<=": function(a, b) { return a <= b; },
    "=": function(a, b) { return Math.abs(a - b) <= 0.000001 },
    ">=": function(a, b) { return a >= b },
    ">": function(a, b) { return a > b }
};

function alertTeamMessage(data, msgarr){
	 var o = data;
	if(typeof(data)=="string"){
		o = $.evalJSON(data);
	}
    if (o) {
        if (o.errorCode&&typeof(TEXT.Alert[o.errorCode])!="undefined") {
            Util.message(TEXT.Alert[o.errorCode]);
        } else {
            if (typeof(o.message)!="undefined"&&o.message != "") {
                Util.message(o.message);
            } else if(msgarr&&msgarr.length>0){
                if (o.result == "success") {
                    Util.message(msgarr[0]);
                } else if(msgarr.length>1){
                    Util.message(msgarr[1]);
                }
            }
        }
        
    }
}
